package com.des1gn.serviceb.config;

import com.alibaba.nacos.common.http.HttpUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName MybatisContext
 * @Description TODO
 * @Author Des1gn
 * @Date 2023/3/8 17:17
 * @Version 1.0
 **/
@Component
@Slf4j
public class MybatisContext implements InitializingBean {

    @Autowired
    DefaultSqlSessionFactory sqlSessionFactory;

    @Autowired
    ApplicationContext applicationContext;

    public static final List<String> urls = new LinkedList<>();

    public void reloadMapper() throws IOException {
        // 清除xml缓存
        synchronized (this.sqlSessionFactory) {
            Configuration targetConfiguration = this.sqlSessionFactory.getConfiguration();
            targetConfiguration.getMapperRegistry().clearCache();
            targetConfiguration.clearMappedStatement();
            for (String url : urls) {
                InputStream urlAsStream = Resources.getUrlAsStream(url);
                try {
                    XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(urlAsStream, targetConfiguration, url,
                            targetConfiguration.getSqlFragments());
                    xmlMapperBuilder.parseMapper();
                } catch (Exception e) {
                } finally {
                    ErrorContext.instance().reset();
                }
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        getXmlFiles();
        reloadMapper();
        log.debug("mybatis xml reload successfull");
    }


    private void getXmlFiles(){
        String urlStr = "http://localhost:8001/demo/mapper/";
        StringBuilder result = new StringBuilder();
        try {
            URI uri = HttpUtils.buildUri(urlStr, null);
            URL url = uri.toURL();
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200){
                InputStream inputStream = urlConnection.getInputStream();
                if (null != inputStream) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                    }
                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String document = result.toString();
        if (StringUtils.isNotEmpty(document)){
            Document dom = Jsoup.parse(document);
            Element body = dom.body();
            Elements aList = body.getElementsByTag("a");
            for (Element element : aList) {
                String href = element.attr("href");
                if (StringUtils.isNotEmpty(href) && !href.equals("../")){
                    urls.add(urlStr.concat(element.text()));
                }
            }
        }
    }
}
